package com.huilian.iotbox.admin.wap.service.impl;

import com.huilian.iotbox.admin.wap.dao.RolePermissionDao;
import com.huilian.iotbox.admin.wap.service.RolePermissionService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author 少凡
 * @date 2020/2/29 10:26
 */
@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private RolePermissionDao rolePermissionDao;

    /**
     * 批量授权
     *
     * @param newPermissionIdList 需要授权的授权列表
     * @param roleId              被授权对象
     * @param userInfo            操作人
     * @return
     */
    @Override
    public ServerResponse authorizeBatch(List<Integer> newPermissionIdList, Integer roleId, UserInfo userInfo) {

        /**
         *  查看角色，现有授权(包括选中和未选中的)
         */
        List<Integer> oldPermissionIdList = rolePermissionDao.findPermissionIdListByRoleId(roleId);

        //交集，原来的，和新传入来的都有此权限(将旧的update checked true)
        List<Integer> intersection = oldPermissionIdList.stream().filter(item -> newPermissionIdList.contains(item)).collect(toList());

        //差集,新传入的不包含旧的，新传入的无，旧的有(将旧的update checked false)
        List<Integer> reduceUpdate = oldPermissionIdList.stream().filter(item -> !newPermissionIdList.contains(item)).collect(toList());

        //差集，旧的没有，新传入的有（insert true）
        List<Integer> reduceInsert = newPermissionIdList.stream().filter(item -> !oldPermissionIdList.contains(item)).collect(toList());

        if (intersection.size() != 0) {
            rolePermissionDao.batchUpdate(intersection, roleId, true);
        }

        if (reduceUpdate.size() != 0) {
            rolePermissionDao.batchUpdate(reduceUpdate, roleId, false);
        }

        if (reduceInsert.size() != 0) {
            rolePermissionDao.batchInsert(reduceInsert, roleId, true);
        }

        return ServerResponse.createBySuccess("授权成功！");
    }

}
